package component

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Reflect"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/periodTask"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEnv"
	"time"
)

type configEntityTask struct {
}

func (e *configEntityTask) TaskType() periodTask.TaskType {
	return periodTask.TaskShare
}

func (e *configEntityTask) SchedulePeriod() int64 {
	return 10
}

func (e *configEntityTask) Execute() {
	dataList := InitialConfigNotifier.getConfigEntity()
	for _, data := range dataList {
		serviceType := data["serviceType"]
		serviceName := data["serviceName"]
		configMap := data["configEntity"]

		if Method.HasNull(serviceType, serviceName, configMap) {
			continue
		}

		// 检查：数据格式是否合法
		if !Reflect.IsString(serviceType) || !Reflect.IsString(serviceName) || !Reflect.IsMap(configMap) {
			continue
		}

		// 检查：是否需要忽略掉该服务的自动化配置
		if e.ignoreConfig(serviceType.(string), serviceName.(string)) {
			continue
		}

		// 将manager-native，重命名为manager-service
		serviceName = edgeEnv.Name.GetAppName(serviceType.(string), serviceName.(string))

		// 注册配置
		e.registerConfigEntity(serviceType.(string), serviceName.(string), configMap.(map[string]interface{}))
	}
	return
}

func (e *configEntityTask) ignoreConfig(serviceType string, serviceName string) bool {
	// 检查：是否是需要进行忽略处理的manager-service 或者是 manager-native
	if !edgeEnv.Name.IsManager(serviceType, serviceName) {
		return false
	}

	// 检查：该服务是否处于运行状态
	value := commRedisStatus.Consumer.GetValue(commRedisStatus.BuildServiceKey(serviceType, serviceName))
	if value == nil {
		return false
	}

	// 检查：该服务的心跳状态，是否处于运行当中
	activeTime := Map.GetInt64(value.(map[string]interface{}), "activeTime", 0)
	now := time.Now().UnixMilli()
	return now-activeTime > int64(60*1000)
}

func (e *configEntityTask) registerConfigEntity(serviceType string, serviceName string, configMap map[string]interface{}) {
	// 定义一个函数级的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			commLogger.Console.Error(fmt.Sprintf("config() 捕获到异常:%v", r))
		}
	}()

	for key, config := range configMap {
		if !Reflect.IsMap(config) {
			continue
		}
		serverConfig := config.(map[string]interface{})

		// 取出配置内容
		remark := serverConfig["remark"]
		configValue := serverConfig["configValue"]
		configParam := serverConfig["configParam"]
		if Method.HasNull(remark, configValue, configParam) {
			continue
		}

		// 检查：数据格式是否合法
		if !Reflect.IsString(remark) || !Reflect.IsMap(configValue) || !Reflect.IsMap(configParam) {
			continue
		}

		configEntity := commRedisService.GetConfigEntity(serviceName, serviceType, key)
		if configEntity == nil {
			newConfig := edgeEntity.Type.ConfigEntity.Instance()
			newConfig.ServiceType = serviceType
			newConfig.ServiceName = serviceName
			newConfig.ConfigName = key
			newConfig.Remark = remark.(string)
			Map.Append(newConfig.ConfigValue, configValue.(map[string]interface{}))
			Map.Append(newConfig.ConfigParam, configParam.(map[string]interface{}))

			commEntityManager.InsertEntity(newConfig)
		}
	}
}
